package com.koron.css2.meterService.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.meterService.bean.MsInfoBean;
import com.koron.css2.meterService.bean.MsInfoChangeBean;
import com.koron.css2.meterService.bean.MsInfoChangeDetailBean;
import com.koron.css2.meterService.mapper.MsInfoChangeDetailMapper;
import com.koron.css2.meterService.mapper.MsInfoChangeMapper;
import com.koron.css2.meterService.mapper.MsInfoTempMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.*;

/**
 * 水表变更修改
 * @author bin
 *
 */
public class WmChgUpdate implements ServerInterface{

	private static Logger log = LogManager.getLogger(WmChgUpdate.class);

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		
		MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "修改成功", Map.class);
		try {
			MsInfoChangeBean bean = JsonUtils.objectToPojo(req.getData(), MsInfoChangeBean.class);
			MsInfoChangeMapper mapper = factory.getMapper(MsInfoChangeMapper.class);
			MsInfoTempMapper msInfoMapper = factory.getMapper(MsInfoTempMapper.class);
			MsInfoChangeDetailMapper detailMapper = factory.getMapper(MsInfoChangeDetailMapper.class);
			List<MsInfoBean> msInfos = bean.getMsInfos();
			bean.setUpdateInfo(userInfo);
			detailMapper.deleteByChangeId(bean.getId());
			int updateAmount = 0;
			int deleteAmount = 0;
			for(MsInfoBean msInfo : msInfos) {
				String billNo = mapper.selectProcessNotEnd(msInfo.getMeterNo(),bean.getId());
				if(billNo!= null) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "该水表存在其它状态的单据", void.class);
				}
			}
			if(msInfoBeanIsRepeat(msInfos)) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "当前变更单据存在重复表身码", void.class);
			};
			MsInfoBean repeat = imeiIsRepeat(msInfos);
			if(repeat != null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "当前变更单据存在重复的IMEI号：" + repeat.getImei(), void.class);
			};
			repeat = imsiIsRepeat(msInfos);
			if(repeat != null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "当前变更单据存在重复的IMSI号：" + repeat.getImsi(), void.class);
			};
			for(MsInfoBean msInfo : msInfos) {
				MsInfoChangeDetailBean detail = new MsInfoChangeDetailBean();
				if(StringUtils.isBlank(msInfo.getMeterModel()))
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表型号不能为空", void.class);
//				if(StringUtils.isBlank(msInfo.getMeterForm()))
					// return MessageBean.create(Constant.MESSAGE_INT_FAIL, "新旧表不能为空", void.class);
				detail.setChangeId(bean.getId());
				detail.setId(Tools.getObjectId());
				detail.setMeterNo(msInfo.getMeterNo());
				detail.setOperateType(msInfo.getOperateType());
				String msInfoId = Tools.getObjectId();
				msInfo.setCreateName(userInfo.getUserInfo().getName());
				msInfo.setId(msInfoId);
				Integer check = msInfoMapper.checkFactoryNo(msInfo.getMeterNo(),msInfo.getFactoryNo());
				if(check!=null && check>0) {
					return MessageBean.create(Constant.MESSAGE_INT_FAIL, "表身码："+msInfo.getFactoryNo()+"已存在", void.class);
				}
				if(StringUtils.isNotBlank(msInfo.getImei())) {
					msInfo.setImei(msInfo.getImei().trim());
					int iCount = msInfoMapper.checkImei(msInfo.getImei(), msInfo.getMeterNo());
					if (iCount > 0){
						return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表库中存在相同的水表IMEI号(" + msInfo.getImei() + ")", Void.class);
					}
				}
				if(StringUtils.isNotBlank(msInfo.getImsi())) {
					msInfo.setImsi(msInfo.getImsi().trim());
					int iCount = msInfoMapper.checkImsi(msInfo.getImsi(), msInfo.getMeterNo());
					if (iCount > 0){
						return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表库中存在相同的水表IMSI号(" + msInfo.getImsi() + ")", Void.class);
					}
				}
				msInfo.setMeterForm(null); //置为NULL
				msInfoMapper.addMsInfoTemp(msInfo);
				detail.setMsInfoId(msInfoId);
				detail.setOperateType(msInfo.getOperateType());
				detailMapper.insert(detail);
				if(msInfo.getOperateType() == 1) {
					updateAmount ++;
				}
				if(msInfo.getOperateType() == 2) {
					deleteAmount ++;
				}
			}
			bean.setDeleteAmount(deleteAmount);
			bean.setUpdateAmount(updateAmount);
			int iCount = mapper.update(bean);
			if(iCount < 1) {
				info.setCode(Constant.MESSAGE_INT_FAIL);
				info.setDescription("修改失败");
			}
			Map<String, String> data = new HashMap<String, String>();
			data.put("id", bean.getId());
			info.setData(data);
		} catch (Exception e) {
			info.setCode(Constant.MESSAGE_INT_FAIL);
			info.setDescription("修改失败");
			log.error(e.getMessage(), e);
		}
		return info;
	}
	private Boolean msInfoBeanIsRepeat(List<MsInfoBean> orderList) {
        Set<MsInfoBean> set = new TreeSet<MsInfoBean>(new Comparator<MsInfoBean>() {
            public int compare(MsInfoBean a, MsInfoBean b) {
                // 字符串则按照asicc码升序排列
                return a.getFactoryNo().compareTo(b.getFactoryNo());
            }
        });
        set.addAll(orderList);
        if (set.size() < orderList.size()) {
            return true;
        }
        return false;
    }

	private MsInfoBean imeiIsRepeat(List<MsInfoBean> list) {
		for (int i = 0; i < list.size(); i++){
			MsInfoBean msInfo1 = list.get(i);
			if (StringUtils.isBlank(msInfo1.getImei()))continue;
			for (int j = i + 1; j < list.size(); j++){
				MsInfoBean msInfo2 = list.get(j);
				if (StringUtils.isBlank(msInfo2.getImei()))continue;
				if (Objects.equals(msInfo1.getImei(), msInfo2.getImei())){
					return msInfo1;
				}
			}
		}
		return null;
	}

	private MsInfoBean imsiIsRepeat(List<MsInfoBean> list) {
		for (int i = 0; i < list.size(); i++){
			MsInfoBean msInfo1 = list.get(i);
			if (StringUtils.isBlank(msInfo1.getImsi()))continue;
			for (int j = i + 1; j < list.size(); j++){
				MsInfoBean msInfo2 = list.get(j);
				if (StringUtils.isBlank(msInfo2.getImsi()))continue;
				if (Objects.equals(msInfo1.getImsi(), msInfo2.getImsi())){
					return msInfo1;
				}
			}
		}
		return null;
	}

}
